package com.common.base.widget;

import android.content.Context;
import android.text.Html;
import android.text.TextUtils;
import android.util.AttributeSet;

import androidx.appcompat.widget.AppCompatTextView;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 对于部分文字标红显示
 */
public class HtmlTextView extends AppCompatTextView {
    public HtmlTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void setText(String srcText, String tagText) {
        if (!TextUtils.isEmpty(srcText) && !TextUtils.isEmpty(tagText)) {
            String result = IgnoreCaseReplace(srcText, tagText);
            if (result.contains("</font>")) {
                setText(Html.fromHtml(result));
            } else {
                setText(result);
            }
        } else {
            setText(srcText);
        }
    }

    /**
     * 不区分大小写高亮替换
     *
     * @param source
     * @param patternstring
     * @return
     */
    public static String IgnoreCaseReplace(String source, String patternstring) {
        Pattern p = Pattern.compile(patternstring, Pattern.CASE_INSENSITIVE);
        Matcher mc = p.matcher(source);
        StringBuffer sb = new StringBuffer();
        while (mc.find()) {
            mc.appendReplacement(sb, "<font color='#FF4A4A'>" + mc.group() + "</font>");
        }
        mc.appendTail(sb);
        return sb.toString();
    }
}
